const app = getApp()

Page({
  data: {
    id: '',
    shop: {
      name: '',
      address: '',
      phone: '',
      description: '',
      logo: '',
      status: 'open'  // open/closed
    }
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      this.loadShop(options.id)
    }
  },

  // 加载店铺信息
  async loadShop(id) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('shops').doc(id).get()
      
      this.setData({ shop: data })
    } catch (error) {
      console.error('加载店铺信息失败：', error)
    }
  },

  // 输入框内容变化
  onInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`shop.${field}`]: value
    })
  },

  // 选择店铺状态
  onStatusChange(e) {
    this.setData({
      'shop.status': e.detail.value ? 'open' : 'closed'
    })
  },

  // 选择店铺logo
  async chooseLogo() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })

      wx.showLoading({ title: '上传中...' })

      const filePath = res.tempFilePaths[0]
      const result = await wx.cloud.uploadFile({
        cloudPath: `shops/${Date.now()}-${Math.floor(Math.random() * 1000)}${filePath.match(/\.[^.]+?$/)[0]}`,
        filePath
      })

      this.setData({
        'shop.logo': result.fileID
      })

      wx.hideLoading()
    } catch (error) {
      console.error('选择/上传logo失败：', error)
      wx.hideLoading()
    }
  },

  // 保存店铺
  async saveShop() {
    const { shop, id } = this.data
    
    // 表单验证
    if (!shop.name || !shop.address || !shop.phone) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    try {
      wx.showLoading({ title: '保存中...' })
      const db = wx.cloud.database()
      
      if (id) {
        // 更新店铺
        await db.collection('shops').doc(id).update({
          data: {
            ...shop,
            updateTime: db.serverDate()
          }
        })
      } else {
        // 新增店铺
        await db.collection('shops').add({
          data: {
            ...shop,
            createTime: db.serverDate(),
            updateTime: db.serverDate()
          }
        })
      }

      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })

      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } catch (error) {
      console.error('保存店铺失败：', error)
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  }
}) 